package com.xss.ipctest.aidl;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.xss.ipctest.R;

import java.util.List;

/**
 * aidl客户端
 */
public class BookManagerActivity extends AppCompatActivity {
    private static final String TAG = "BookManagerActivity";
    private static final int MESSAGE_NEW_BOOK_ARRIVED = 1;
    private IBookManager mRemoteBookManager;
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MESSAGE_NEW_BOOK_ARRIVED:
                    Log.i(TAG, "handleMessage: receive new book:"+msg.obj);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    };
    private IOnNewBookArrivedListener mOnNewBookArrivedListener=new IOnNewBookArrivedListener.Stub() {
        //当有新书时，服务端回调该方法
        // 该方法是在Binder线程池中执行的，未方便UI操作需要使用handler切回主线程
        @Override
        public void onNewBookArrived(Book newBook) throws RemoteException {
            mHandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVED,newBook).sendToTarget();
        }
    };
    private ServiceConnection conn = new ServiceConnection() {
        //绑定成功
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //将服务端返回的Binder转换成AIDL接口
            IBookManager iBookManager = IBookManager.Stub.asInterface(service);
            mRemoteBookManager=iBookManager;
            try {
                //通过AIDL接口访问服务端远程方法
                List<Book> list = iBookManager.getBookList();
                Log.i(TAG, "onServiceConnected: query book list,list type:"
                        + list.getClass().getCanonicalName());
                Log.i(TAG, "onServiceConnected: query book list:" + list.toString());

                Book newBook = new Book(3, "Android开发艺术探索");
                iBookManager.addBook(newBook);
                Log.i(TAG, "onServiceConnected: add Book:" + newBook);
                List<Book> newList = iBookManager.getBookList();
                Log.i(TAG, "onServiceConnected: query book list:" + newList.toString());
                //客户端注册IOnNewBookArrivedListener到远程服务器
                iBookManager.registerListener(mOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mRemoteBookManager=null;
            Log.d(TAG, "onServiceDisconnected. tname:" + Thread.currentThread().getName());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_manager);
        //绑定远程服务
        Intent intent = new Intent(this, BookManagerService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

    public void onButton1Click(View view){
        Toast.makeText(this, "单击按钮", Toast.LENGTH_SHORT).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mRemoteBookManager!=null){
                    try {
                        List<Book> newList=mRemoteBookManager.getBookList();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除注册
        if (mRemoteBookManager != null
                && mRemoteBookManager.asBinder().isBinderAlive()) {
            try {
                Log.i(TAG, "onDestroy: unregister listener:" + mOnNewBookArrivedListener);
                mRemoteBookManager.unregisterListener(mOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(conn);
    }
}
